#include <opencv2/opencv.hpp>
#include <iostream>
#include <thread>

void captureVideo(int cameraIndex) {
    // 创建视频捕捉对象
    cv::VideoCapture cap(cameraIndex);

    if (!cap.isOpened()) {
        std::cerr << "Error: Unable to open camera " << cameraIndex << std::endl;
        return;
    }

    cv::Mat frame;
    std::string windowName = "Camera " + std::to_string(cameraIndex);

    // 创建窗口
    cv::namedWindow(windowName);

    while (true) {
        // 从摄像头读取一帧
        cap >> frame;
        if (frame.empty()) {
            std::cerr << "Warning: Empty frame from camera " << cameraIndex << std::endl;
            break;
        }

        // 显示帧
        cv::imshow(windowName, frame);

        // 按'q'退出循环
        if (cv::waitKey(1) == 'q') {
            break;
        }
    }

    // 释放视频捕捉对象
    cap.release();
    // 销毁窗口
    cv::destroyWindow(windowName);
}

int main() {
    // 创建两个线程，每个线程处理一个摄像头
    std::thread camera0Thread(captureVideo, 0);
    std::thread camera1Thread(captureVideo, 1);

    // 等待线程结束
    camera0Thread.join();
    camera1Thread.join();

    return 0;
}